import { NavBar, InfiniteScroll } from 'antd-mobile'
import { useHistory, useParams } from 'react-router-dom'
import classNames from 'classnames'
import styles from './Article.module.scss'

import { CommentItem } from './Channels/CommentItem/CommentItem'
import { CommentFooter } from './Channels/CommentFooter/CommentFooter'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { followAuthor, getArticleById } from '@/store/actions/article'
import { RootState } from '@/types/store'
import DOMPurify from 'dompurify'
import 'highlight.js/styles/github.css' // 只要导入这个样式即可
import highlight from 'highlight.js'
import ContentLoader from 'react-content-loader'
import { throttle } from 'lodash'
export const Article = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  // 页面状态 获取文章详情
  const params = useParams<{ id: string }>()
  // 页面加载状态
  const [isLoading, setIsLoading] = useState(true)
  useEffect(() => {
    const fetchData = async () => {
      console.log('获取文章详情')
      await dispatch(getArticleById(params.id))
      setIsLoading(false)
    }
    fetchData()
  }, [params.id, dispatch])

  // 解构出文章详情
  const { detail } = useSelector((state: RootState) => state.article)

  // 文章详情 代码内容 高亮
  useEffect(() => {
    const dgHtmlDOM = document.querySelector('.dg-html')
    const codes = dgHtmlDOM?.querySelectorAll<HTMLElement>('pre code')
    // console.log(codes)
    if (codes && codes.length > 0) {
      codes.forEach((el) => {
        // 让每个 code 内容实现代码高亮
        highlight.highlightElement(el)
      })
      return
    }

    highlight.configure({
      // 忽略警告
      ignoreUnescapedHTML: true,
    })

    // 直接找到所有的 pre 标签
    const pres = dgHtmlDOM?.querySelectorAll('pre')
    if (pres && pres.length > 0) {
      pres.forEach((el) => {
        highlight.highlightElement(el)
      })
    }
  }, [detail])

  const loadMoreComments = async () => {
    console.log('加载更多评论')
  }

  // 文章详情ref
  const wrapperRef = useRef<HTMLDivElement>(null)
  // 作者详情ref
  const authorRef = useRef<HTMLDivElement>(null)
  // 作者信息是否显示在标题栏的状态
  const [isShowAuthor, setIsShowAuthor] = useState(false)
  // wrapperRef 滚动事件监听
  useEffect(() => {
    // 获取原生 DOM 的异常处理
    const wrapper = wrapperRef.current
    if (!wrapper) return
    const author = authorRef.current
    if (!author) return

    // wrapper 滑动要计算author距离顶部的距离
    const wrapperOnScroll = throttle(() => {
      const top = author.getBoundingClientRect().top
      // console.log('wrapper 滚动,作者距离顶部的距离', top)
      if (top < 11) {
        // 标题栏显示作者
        setIsShowAuthor(true)
      } else {
        // 不显示作者
        setIsShowAuthor(false)
      }
    }, 300)
    wrapper.addEventListener('scroll', wrapperOnScroll)
    return () => {
      wrapper.removeEventListener('scroll', wrapperOnScroll)
    }
  })
  // 渲染文章详情
  const renderArticle = () => {
    // 文章详情
    if (isLoading) {
      return (
        // 根据当前页面结构，设计好的 loading 效果
        <ContentLoader
          speed={2}
          width={375}
          height={230}
          viewBox="0 0 375 230"
          backgroundColor="#f3f3f3"
          foregroundColor="#ecebeb">
          <rect x="16" y="8" rx="3" ry="3" width="340" height="10" />
          <rect x="16" y="26" rx="0" ry="0" width="70" height="6" />
          <rect x="96" y="26" rx="0" ry="0" width="50" height="6" />
          <rect x="156" y="26" rx="0" ry="0" width="50" height="6" />
          <circle cx="33" cy="69" r="17" />
          <rect x="60" y="65" rx="0" ry="0" width="45" height="6" />
          <rect x="304" y="65" rx="0" ry="0" width="52" height="6" />
          <rect x="16" y="114" rx="0" ry="0" width="340" height="15" />
          <rect x="263" y="208" rx="0" ry="0" width="94" height="19" />
          <rect x="16" y="141" rx="0" ry="0" width="340" height="15" />
          <rect x="16" y="166" rx="0" ry="0" width="340" height="15" />
        </ContentLoader>
      )
    } else {
      return (
        <div className="wrapper" ref={wrapperRef}>
          <div className="article-wrapper">
            <div className="header">
              <h1 className="title">{detail.title}</h1>

              <div className="info">
                <span>{detail.pubdate}</span>
                <span>{detail.read_count} 阅读</span>
                <span>{detail.comm_count} 评论</span>
              </div>

              <div className="author" ref={authorRef}>
                <img
                  src={
                    detail.aut_photo ||
                    'http://geek.itheima.net/images/user_head.jpg'
                  }
                  alt=""
                />
                <span className="name">{detail.aut_name}</span>
                <span
                  className={classNames(
                    'follow',
                    detail.is_followed ? 'followed' : ''
                  )}
                  onClick={handleFollow}>
                  {detail.is_followed ? '已关注' : '关注'}
                </span>
              </div>
            </div>

            <div className="content">
              <div
                className="content-html dg-html"
                dangerouslySetInnerHTML={{
                  __html: DOMPurify.sanitize(detail.content),
                }}
              />
              <div className="date">发布文章时间：{detail.pubdate}</div>
            </div>
          </div>

          <div className="comment" id="plwz" ref={commentRef}>
            <div className="comment-header">
              <span>全部评论（{detail.comm_count}）</span>
              <span>{detail.like_count} 点赞</span>
            </div>

            <div className="comment-list">
              <CommentItem />
              <CommentItem /> <CommentItem /> <CommentItem />
              <CommentItem /> <CommentItem /> <CommentItem />
              <InfiniteScroll hasMore={false} loadMore={loadMoreComments} />
            </div>
          </div>
        </div>
      )
    }
  }

  const commentRef = useRef<HTMLDivElement>(null)
  const isShowComment = useRef(false)
  const [wz, setWz] = useState(0)
  // 展示 or 隐藏评论内容
  const onShowComment = () => {
    // console.log('评论按钮被点击了')
    const wrapper = wrapperRef.current
    if (!wrapper) return
    const comment = commentRef.current
    if (!comment) return
    // 评论区举例顶部的举例
    const commentTop = comment.getBoundingClientRect().top
    const gao = document.getElementById('plwz')?.clientHeight
    // 将wrapper直接偏移这个举例即可
    if (commentTop > 385) {
      setWz(wrapper.scrollTop)
      wrapper.scrollTo(
        gao
          ? { top: wrapper.scrollHeight - gao - 45 }
          : { top: wrapper.scrollHeight }
      )
    } else {
      wrapper.scrollTo({ top: 180 })
      // wrapper.scrollTo({ top: wz })
    }

    // 用户点击评论后，这个距离会重新计算，所以下次偏移就是当前评论区距离顶部的距离。
  }
  // 关注点击事件
  const handleFollow = () => {
    dispatch(followAuthor(detail.aut_id, detail.is_followed))
  }
  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <svg className="icon">
                <use xlinkHref={'#icongengduo'}></use>
              </svg>
            </span>
          }>
          {isShowAuthor && (
            <div className="nav-author">
              <img
                src={
                  detail.aut_photo ||
                  'http://geek.itheima.net/images/user_head.jpg'
                }
                alt=""
              />
              <span className="name">{detail.aut_name}</span>
              <span
                className={classNames('follow', {
                  followed: detail.is_followed,
                })}
                onClick={handleFollow}>
                {detail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {/* 文章详情和评论 */}
        {renderArticle()}

        {/* 底部评论栏 */}
        <CommentFooter onShowComment={onShowComment} />
      </div>
    </div>
  )
}
